package com.water.cglib;

import com.water.aop.Aop;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author wsj
 * @version 1.0
 * @description: TODO
 * @date 2022/1/11 21:20
 */
public class CglibProxyFactory {
    private NBAService nbaService;//没有实现接口的类
    private Aop aop;

    public CglibProxyFactory(NBAService nbaService,Aop aop){
        this.aop = aop;
        this.nbaService = nbaService;
    }

    public Object getProxyInstance(){
        //不需要业务方法实现接口，直接增强
        return Enhancer.create(nbaService.getClass(),
                new MethodInterceptor() {
                    @Override
                    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                        try {
                            aop.before();
                            Object invoke = methodProxy.invokeSuper(o, objects);
                            aop.after();
                            return invoke;
                        } catch (Exception e) {
                            aop.exception();
                            throw e;
                        } finally {
                            aop.myFinally();
                        }
                    }
                });
    }
}
